package de.baumann.browser.api.net.base;

import android.content.Context;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import de.baumann.browser.OdinApplication;
import de.baumann.browser.utils.MD5Util;
import de.baumann.browser.utils.UserDataKt;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RequestInterceptor implements Interceptor {
    private static String SALTSTR = "06fb7dcb9d4248c5b3bfa5cea9d2000";
    private static final String POST = "POST";
    private static final String GET = "GET";
    private Context context;

    @Override
    public Response intercept(Chain chain) throws IOException {
        context = OdinApplication.getInstance();

        Request request = chain.request();

        if (request.method().equals(GET)) {
            request = addGetParams(request);
        } else if (request.method().equals(POST)) {
            request = addPostParams(request);
        }

        return chain.proceed(request);
    }

    private Request addGetParams(Request request) {
        HttpUrl httpUrl = request.url()
                .newBuilder()
                .addQueryParameter("device_type", OdinUtil.getDeviceType())
                .addQueryParameter("device_uuid", OdinUtil.getDeviceUUID(context))
                .addQueryParameter("system_version", OdinUtil.getSystemVersion())
                .addQueryParameter("app_version", OdinUtil.getAppVersion())
                .addQueryParameter("lang", OdinUtil.getLang())
                .addQueryParameter("pkg_id", OdinUtil.getPackageId(context))
                .addQueryParameter("timestamp", OdinUtil.getTimestamp())
                .addQueryParameter("client_ip", OdinUtil.getIPAddress(context))
                .addQueryParameter("system_type", OdinUtil.getSystemType())
                .addQueryParameter("token", UserDataKt.getToken())
                .addQueryParameter("userId", UserDataKt.getUserId())
                .build();
        Set<String> nameSet = httpUrl.queryParameterNames();
        ArrayList<String> nameList = new ArrayList<>(nameSet);
        Collections.sort(nameList);
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < nameList.size(); i++) {
            try {
                buffer.append(java.net.URLDecoder.decode(nameList.get(i), "UTF-8"))
                        .append("=")
                        .append(httpUrl.queryParameter(nameList.get(i)))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        if (buffer.length() > 0) {
            buffer.deleteCharAt(buffer.length() - 1);
        }

        buffer.append(SALTSTR);
        httpUrl = httpUrl.newBuilder()
                .addQueryParameter("sign", MD5Util.md5encode(buffer.toString(), "UTF-8"))
                .build();
        request = request.newBuilder().url(httpUrl).build();
        return request;
    }

    private Request addPostParams(Request request) throws UnsupportedEncodingException {
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        FormBody formBody;
        if (request.body() instanceof FormBody) {
            formBody = (FormBody) request.body();
            for (int i = 0; i < formBody.size(); i++) {
                bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
            }
        }

        formBody = bodyBuilder
                .addEncoded("device_type", OdinUtil.getDeviceType())
                .addEncoded("device_uuid", OdinUtil.getDeviceUUID(context))
                .addEncoded("system_version", OdinUtil.getSystemVersion())
                .addEncoded("app_version", OdinUtil.getAppVersion())
                .addEncoded("lang", OdinUtil.getLang())
                .addEncoded("pkg_id", OdinUtil.getPackageId(context))
                .addEncoded("timestamp", OdinUtil.getTimestamp())
                .addEncoded("client_ip", OdinUtil.getIPAddress(context))
                .addEncoded("system_type", OdinUtil.getSystemType())
                .addEncoded("token", UserDataKt.getToken())
                .addEncoded("userId", UserDataKt.getUserId())
                .build();


        SortedMap<String, Object> boyMap = new TreeMap<>();

        for (int i = 0; i < formBody.size(); i++) {
            String encodeName = formBody.encodedName(i);
            String encodeValue = formBody.encodedValue(i);
            boyMap.put(encodeName, URLDecoder.decode(encodeValue, "UTF-8"));
        }
        Set set = boyMap.entrySet();

        StringBuilder builder = new StringBuilder();

        for (Object aSet : set) {
            Map.Entry entry = (Map.Entry) aSet;
            String k = (String) entry.getKey();
            Object v = entry.getValue();
            builder.append(java.net.URLDecoder.decode(k, "UTF-8")).append("=").append(v).append("&");
        }

        if (builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        builder.append(SALTSTR);

        formBody = bodyBuilder.
                addEncoded("sign", MD5Util.md5encode(builder.toString(), "UTF-8"))
                .build();
        request = request.newBuilder().post(formBody).build();
        return request;
    }

}
